﻿using DCommon.Caching.Sample.Models;
using System;
using System.Collections.Generic;

namespace DCommon.Caching.Sample
{
    class PostManager
    {
        private Random m_Random;
        private ICache m_Cache;

        public PostManager(CacheFactory cacheFactory)
        {
            m_Random = new Random();
            m_Cache = cacheFactory.GetCache("Post");
        }

        public IEnumerable<Post> GetPosts(IEnumerable<string> ids)
        {
            var posts = new List<Post>();
            foreach (var id in ids)
            {
                var valueTypeKey = id + "valuetype";
                var valueKey = id + "value";
                var valueType = m_Cache.Get<string>(valueTypeKey);
                if (valueType == null)
                {
                    var destinaion = GetPost(id);
                    m_Cache.Set(valueTypeKey, destinaion.GetType().FullName);
                    m_Cache.Set(valueKey, destinaion);
                    posts.Add(destinaion);
                }
                else
                {
                    var destinaion = (Post)m_Cache.Get(valueKey, Type.GetType(valueType));
                    posts.Add(destinaion);
                }
            }
            return posts;
        }

        private Post GetPost(string id)
        {
            var i = m_Random.Next(1, 3);
            switch (i)
            {
                case 1:
                    return GetMoive(id);
                case 2:
                    return GetGallery(id);
                case 3:
                default:
                    return GetMoive(id);
            }
        }

        private Movie GetMoive(string id)
        {
            return new Movie
            {
                Created = DateTime.Now,
                Updated = DateTime.Now,
                Name = id,
                Description = id,
                Actors = new[] { "actor1", "actor2", "actor3" },
                Clips = new[] { "clip1", "clip2", "clip3" },
            };
        }

        private Gallery GetGallery(string id)
        {
            return new Gallery
            {
                Created = DateTime.Now,
                Updated = DateTime.Now,
                Name = id,
                Description = id,
                Pictures = new[] { "picture1", "picture2", "picture3" },
            };
        }

        private Article GetArticle(string id)
        {
            return new Article
            {
                Created = DateTime.Now,
                Updated = DateTime.Now,
                Name = id,
                Description = id,
                Author = "author",
            };
        }
    }
}
